<?php
declare (strict_types = 1);

namespace command\logic;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;

class LogicCreate extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('logic:create')
            ->addArgument('module', Argument::OPTIONAL, "app module name")
            ->addOption('logics', null, Option::VALUE_REQUIRED, 'op logic list')
            ->setDescription('auto create logic');        
    }

    protected function execute(Input $input, Output $output)
    {
        $module = $input->getArgument('module');

        //获取项目配置，根据项目配置写入逻辑方法
        $projectFile = $this->app->getBasePath().DIRECTORY_SEPARATOR.'Project.php';
        if(is_file($projectFile)){
            $projectConfig = include_once $projectFile;
            $logicConfigList = $module?($projectConfig[$module]['logic']??[]):($projectConfig['logic']??[]);
        }else{
            $logicConfigList = [];
        }

        if(empty($logicConfigList)){
            $output->writeln('logic config is empty');
            return true;
        }

        $modulePath = $module?$module."/":'';

        if ($input->hasOption('logics')) {
            $logics = $input->getOption('logics');
            $logics = explode(',',$logics);
        }else{
            $logics = [];
        }


        $path = $this->app->getBasePath().$modulePath."logic";

        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }

        $stub = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'logic.stub');

       
        foreach ($logicConfigList as $logicName => $config) {

            $namespace = 'app\logic';

            if($module)$namespace = 'app\\'.$module.'\logic';

            $pathName = $path . DIRECTORY_SEPARATOR . $logicName ."Logic.php";

            if(is_file($pathName))continue;//文件已存在跳过

            $method = $this->buildMethod($config['logic_model']);

            file_put_contents(
                $pathName,
                str_replace(
                    ['{$namespace}','{$use}','{$comment}','{$logicName}','{$logicMethod}'],
                    [$namespace,$method['use_str'],$config['comment'],$logicName,$method['method_str']],
                    $stub
                )
            );

        }

    	// 指令输出
    	$output->writeln('logic');
    }

    /**
     * 构建逻辑处理方法
     *
     * @param array $modelConfig
     * @param string $modelName
     * @return void
     */
    private function buildMethod($logicModel)
    {
        $use = [];
        $functions = [];
        foreach ($logicModel as $model=>$config) {
            if(empty($config['functions']))continue;
            $use[]='use '.($config['namespace']??'app\\model').'\\'.$model.';';

            foreach ($config['functions'] as $type => $value) {
                $tplFile = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'method' . DIRECTORY_SEPARATOR . $type . '.stub';
                if(is_file($tplFile)){
                    $tplstr = file_get_contents($tplFile);
                    $functions[]=str_replace(
                        ['{$comment}','{$methodName}','{$model}','{$pk}','{$allowField}','{$with}','{$order}','{$wconfig}'],
                        [$config['comment'],lcfirst($model),$model,$config['pk'],$value['allowField']??'[]',$value['with']??'""',$value['order']??'""',$value['wconfig']??'[]'],
                        $tplstr
                    );
                }
            }
            
        }

        $res['method_str'] = implode(PHP_EOL.PHP_EOL,$functions);
        $res['use_str'] = implode(PHP_EOL,$use);

        return $res;

    }
}
